<?php

namespace App\Http\Controllers\Api\V1;

use App\Events\GameFinish;
use App\Models\ChildPlay;
use App\Models\Device;
use App\Models\File as FileModel;
use App\Models\Game;
use App\Models\History;
use App\Support\ChunkUpload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use mysql_xdevapi\Exception;
use Symfony\Component\Process\Process;

class ImageController extends BaseController
{
    private $cache_head = "child_play";

    public function index()
    {
        $data = $this->getUser();

        return $this->json([$data], 'success', 2000);
        //return $this->json(['user' => $this->user, 'success', 2000]);
    }

    //存储图片
    public function store(Request $request){
        $validate = [
            'device_code' => 'required|string|exists:devices,code',
            'child_id' => 'required|integer|exists:children,id',
            'img' => 'image'
        ];

        $this->validate($request, $validate, [], [
            'device_code' => 'required|string|exists:devices,code',
            'child_id' => 'required|integer|exists:children,id',
            'img' => __('Img')
        ]);
        $data = $request->only(['device_code', 'child_id']);

        if (!$request->hasFile('img')) {
            return $this->json([], config("apicode.paramError.msg"), config("apicode.paramError.code"));
        }

        $file = $request->file('img');
        $uploader = new ChunkUpload();
        $filePath = $uploader->upload($file,'image', date("Ymd").'/'.$data['child_id']);

        if ($filePath === false) {
            return $this->json([], config("apicode.serverError.msg"), config("apicode.serverError.code"));
        }

        $key = cacheHead($this->cache_head). "_".  $data['device_code']."_images";
        $images = Cache::get($key, []);

        $images[] = $filePath;

        if (!Cache::put($key, $images)){
            return $this->json([], config("apicode.serverError.msg"), config("apicode.serverError.code"));
        }

        return $this->json(['url'=>FileModel::getFileUrl($filePath)]);

    }
}
